import React, { Component } from 'react'
import { getPicture, reqCheck } from '../api/base.js'
import { CSSTransition } from 'react-transition-group';
import '@/assets/index.css';
import defaultImg from '@/assets/images/default_1.png'
// import defaultImg from '@/assets/images/default.jpg'
import { aesEncrypt } from "../api/ase.js";
import { connect } from 'dva';
import { Icon } from 'antd'
import ReactDOM from 'react-dom';
// import {RightOutlined } from '@ant-design/icons'
@connect(({ VerifyCode, }) => ({
  VerifyCode,
  getVerify: VerifyCode.getVerify,
  checkVerify: VerifyCode.checkVerify,
}))
class VerifySlide extends Component {
  constructor(props) {
    super(props)
    this.state = {
      blockSize: {
        width: '50px',
        height: '50px'
      },
      setSize: {
        imgHeight: 200,
        imgWidth: 310,
        barHeight: 40,
        barWidth: 310,
      },
      backImgBase: '', // 验证码背景图片
      blockBackImgBase: '', // 验证滑块的背景图片
      backToken: '', // 后端返回的唯一token值
      startMoveTime: "",    //移动开始的时间
      endMovetime: '',      //移动结束的时间
      tipsBackColor: '',    //提示词的背景颜色
      secretKey: '', //后端返回的加密秘钥 字段
      captchaType: 'blockPuzzle',
      moveBlockBackgroundColor: 'rgb(255, 255, 255)',
      leftBarBorderColor: '#EEEEEE',
      leftArrows: '#6F757B',
      leftAreaColor: '#fff',
      iconColor: '',
      barAreaLeft: 0,
      barAreaOffsetWidth: 0,
      startLeft: null,
      moveBlockLeft: null,
      leftBarWidth: null,
      status: false,	    //鼠标状态
      isEnd: false,		//是够验证完成
      passFlag: '',
      tipWords: '',
      text: '向右滑动完成验证',
    }

  }

  componentDidMount() {
    this.uuid()
    this.getData()
    this.init()
  }
  // 初始话 uuid 
  uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var slider = 'slider' + '-' + s.join("");
    var point = 'point' + '-' + s.join("");
    // 判断下是否存在 slider
    // console.log(localStorage.getItem('slider'))
    if (!localStorage.getItem('slider')) {
      localStorage.setItem('slider', slider)
    }
    if (!localStorage.getItem('point')) {
      localStorage.setItem("point", point);
    }
  }
  init() {
    var _this = this

    window.removeEventListener("touchmove", function (e) {
      _this.move(e);
    });
    window.removeEventListener("mousemove", function (e) {
      _this.move(e);
    });

    //鼠标松开
    window.removeEventListener("touchend", function () {
      _this.end();
    });
    window.removeEventListener("mouseup", function () {
      _this.end();
    });

    window.addEventListener("touchmove", function (e) {
      _this.move(e);
    });
    window.addEventListener("mousemove", function (e) {
      _this.move(e);
    });

    //鼠标松开
    window.addEventListener("touchend", function () {
      _this.end();
    });
    window.addEventListener("mouseup", function () {
      _this.end();
    });
  }
  getData() {
    const { dispatch } = this.props
    const params = {
      captchaType: this.state.captchaType,
      clientUid: localStorage.getItem('slider'),
      ts: Date.now(),
    }
    dispatch({
      type: 'VerifyCode/getVerify',
      payload: params,
      callback: (res) => {
        if (res.repCode == '0000') {
          this.setState({
            backImgBase: res.repData.originalImageBase64,
            blockBackImgBase: res.repData.jigsawImageBase64,
            backToken: res.repData.token,
            secretKey: res.repData.secretKey
          })
        }
        // 请求次数超限
        if (res.repCode == '6201') {
          this.setState({
            backImgBase: null,
            blockBackImgBase: null,
            leftBarBorderColor: '#d9534f',
            iconColor: '',
            iconClass: 'icon-close',
            passFlag: false,
            tipWords: res.repMsg
          })
          setTimeout(() => {
            this.setState({
              tipWords: ''
            })
          }, 1000);
        }

      }
    })

  }
  refresh = (isTrue) => {
    !isTrue&&this.getData()
    this.setState({
      moveBlockLeft: '',
      leftBarWidth: null,
      text: '向右滑动完成验证',
      moveBlockBackgroundColor: '#fff',
      leftBarBorderColor: '#EEEEEE',
      leftAreaColor: '#fff',
      leftArrows: '#6F757B',
      iconColor: '',
      status: false,
      isEnd: false
    })
  }
  setBarArea = (event) => {
    let barAreaLeft = parseInt(event && event.getBoundingClientRect().left)
    let barAreaOffsetWidth = event && event.offsetWidth
    // console.log('barAreaOffsetWidth',barAreaLeft)
    this.state.barAreaLeft = barAreaLeft
    this.state.barAreaOffsetWidth = barAreaOffsetWidth
  }

  start = (e) => {
    e = e || window.event
    if (!e.touches) {  //兼容PC端 
      // var x = e.clientX;
      var x = e.clientX - 10
    } else {           //兼容移动端
      var x = e.touches[0].pageX;
    }
    this.setState({
      startLeft: Math.floor(x - this.state.barAreaLeft),
      startMoveTime: +new Date()
    })
    // this.state.startLeft = Math.floor(x - this.state.barAreaLeft);
    // this.state.startMoveTime = +new Date();    //开始滑动的时间
    if (this.state.isEnd == false) {
      this.setState({
        text: '',
        moveBlockBackgroundColor: '#1294FE',
        leftBarBorderColor: '#5cb85c',
        leftArrows: '#fff',
        leftAreaColor: '#D0E8FF',
        iconColor: '',
        status: true
      })
      this.text = ''
      e.stopPropagation();
    }
  }

  move = (e) => {
    e = e || window.event;
    const { startLeft } = this.state
    if (this.state.status && this.state.isEnd == false) {
      if (!e.touches) {
        //兼容PC端
        var x = e.clientX - 10;
      } else {
        //兼容移动端
        var x = e.touches[0].pageX;
      }
      if (x < this.state.barAreaLeft) {
        this.setState({
          moveBlockLeft: '',
          leftBarWidth: null,
          text: '向右滑动完成验证',
          moveBlockBackgroundColor: '#52CCBA',
          leftBarBorderColor: '#EEEEEE',
          leftAreaColor: '#D2F4EF',
          
          iconColor: '',
          status: false,
          isEnd: false
        })
        // this.refresh()
        return;
      }
      var bar_area_left = parseInt(this.state.barAreaLeft);
      var move_block_left = parseInt(x - bar_area_left); //小方块相对于父元素的left值
      if (move_block_left >= this.state.barAreaOffsetWidth - parseInt(parseInt(this.state.blockSize.width) / 2) - 2) {
        move_block_left = this.state.barAreaOffsetWidth - parseInt(parseInt(this.state.blockSize.width) / 2) - 2;
      }

      if (move_block_left <= 0) {
        move_block_left = parseInt(this.state.blockSize.width / 2);
      }

      // console.log(bar_area_left,'bar_area_left',move_block_left)
      //拖动后小方块的left值
      let _moveBlockLeft = (move_block_left - this.state.startLeft) + "px"
      let _leftBarWidth = (move_block_left - this.state.startLeft) + "px"
      this.setState({
        moveBlockLeft: _moveBlockLeft,
        leftBarWidth: _leftBarWidth
      })
    }
  }

  end = () => {
    const { onOk } = this.props
    this.state.endMovetime = +new Date();

    var _this = this;
    //判断是否重合
    if (this.state.status && this.state.isEnd == false) {
      var moveLeftDistance = parseInt((this.state.moveBlockLeft || '').replace('px', ''));
      moveLeftDistance = moveLeftDistance * 310 / parseInt(this.state.setSize.imgWidth)
      let data = {
        captchaType: this.state.captchaType,
        "pointJson": this.state.secretKey ? aesEncrypt(JSON.stringify({ x: moveLeftDistance, y: 5.0 }), this.state.secretKey) : JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
        "token": this.state.backToken,
        clientUid: localStorage.getItem('slider'),
        ts: Date.now()
      }
      const { dispatch } = this.props
      dispatch({
        type: "VerifyCode/checkVerify",
        payload: data,
        callback: (res) => {
          if (res.repCode == "0000") {
            this.setState({
              tipWords: `${((this.state.endMovetime - this.state.startMoveTime) / 1000).toFixed(2)}s验证成功`,
              moveBlockBackgroundColor: '#52CCBA',
              leftBarBorderColor: '#52CCBA',
              leftAreaColor:'#D2F4EF',
              iconColor: '',
              isEnd: true,
              passFlag: true,
            })
            setTimeout(() => {
              this.setState({ tipWords: "" })
              onOk()
              this.refresh(true);
            }, 1000)
          } else {
            this.setState({
              isEnd: true,
              moveBlockBackgroundColor: '#d9534f',
              leftBarBorderColor: '#d9534f',
              leftAreaColor:'#F1C0BF',
              leftArrows: '#fff',
              iconColor: '',
              iconClass: 'icon-close',
              passFlag: false,
              tipWords: res.repMsg || '验证失败'
            })
            setTimeout(() => {
              this.refresh();
              this.setState({
                tipWords: ''
              })
            }, 1000);
          }
        }

      })

      this.state.status = false;
    }

  }

  render() {
    const { mode, captchaType, vSpace, barSize, showRefresh, transitionWidth, finishText, transitionLeft } = this.props;
    const { tipWords, leftArrows, leftAreaColor, } = this.state
    let isSuccess = tipWords.indexOf('验证成功') != -1
    let _style = {
      position: 'absolute',
      width: '310px',
      height: '40px',
      lineHeight: '40px',
      textAlign: 'center',
      color: '#ffffff',
      backgroundColor: isSuccess ? '#5cb85c' : '#FF0000',
      opacity: this.state.tipWords.length > 0 ? '0.7' : '0',
      transitionProperty: 'all',
      transitionDuration: '0.5s',
      bottom: this.state.tipWords.length > 0 ? '45px' : '30px',
      // bottom:'50px',
    }
    return (
      <div style={{ position: 'relative' }} className='stop-user-select'>
        <div
          className='verify-img-out'
          style={{ height: (this.state.setSize.imgHeight) + vSpace }}
        >
          <div
            className='verify-img-panel'
            style={{ width: this.state.setSize.imgWidth, height: this.state.setSize.imgHeight }}
          >
            {this.state.backImgBase ? <img
              src={'data:image/png;base64,' + this.state.backImgBase}
              alt=""
              style={{ width: '100%', height: '100%', display: 'block' }}
            /> : <img
                src={defaultImg}
                alt=""
                style={{ width: '100%', height: '100%', display: 'block' }}
              />}
            <div
              className='verify-refresh'
              onClick={() => this.refresh()}
            >
              <i className='iconfont icon-refresh'></i>
            </div>
            {/* <CSSTransition
              in={this.state.tipWords.length>0} timeout={150} classNames="tips" unmountOnExit
            >
              <span
                className={
                  this.state.passFlag
                    ? `${'verify-tips'} ${'suc-bg'}`
                    : `${'verify-tips'} ${'err-bg'}`
                }
              >
                {this.state.tipWords}
              </span>
            </CSSTransition> */}

            {/* 验证结果的上滑提示条 */}
            <span
              className={
                this.state.passFlag
                  ? `${'verify-tips'} ${'suc-bg'}`
                  : `${'verify-tips'} ${'err-bg'}`
              }
              style={_style}
            >
              {this.state.tipWords}
            </span>
          </div>
        </div>

        <div
          className='verify-bar-area'
          style={{
            width:( +this.state.setSize.imgWidth+1),
            height: barSize.height,
            lineHeight: barSize.height,
            boxSizing:'content-box',
            backgroundColor: "#F7F9FA",
            borderStyle: "solid",
            borderWidth: "0.5px",
            borderColor: "#E4E7EB",
            borderRadius: '5px',
          }}
          ref={(bararea) => this.setBarArea(bararea)}
        >
          <span className='verify-msg' style={{ marginLeft: '100px' }}>{this.state.text}</span>
          {/* 滑动后左边的div */}
          <div
            className='verify-left-bar'
            style={{
              position: 'relative',
              bottom: '40px',
              width: this.state.leftBarWidth?this.state.leftBarWidth:barSize.height,
              height: barSize.height,
              // borderColor: this.state.leftBarBorderColor,
              backgroundColor: this.state.leftAreaColor,
              // transaction: transitionWidth,
            }}
          >
            <span className='verify-msg'>{finishText}</span>
            {/* 拖动的滑块 */}
            <div
              className='verify-move-block'
              onTouchStart={(e) => this.start(e)}
              onMouseDown={(e) => this.start(e)}
              style={{
                position: 'absolute',
                width: barSize.height,
                height: barSize.height,
                backgroundColor: this.state.moveBlockBackgroundColor,
                left: this.state.moveBlockLeft,
                transition: transitionLeft,
                borderStyle: "solid",
                borderWidth: "0.5px",
                borderColor: "#E4E7EB",
                borderRadius: '5px',
              }}
            >
              <i
                className='verify-icon iconfont icon-right'
                style={{
                  color: this.state.iconColor,
                  fontSize: '16px',
                  textAlign: "center",
                  paddingLeft: "12px",

                }}
              >
               {leftAreaColor!=='#F1C0BF'? <Icon type="arrow-right" style={{ zIndex: '200', color: leftArrows }} />
                :<Icon type="close" style={{ zIndex: '200', color: leftArrows ,}} />}
              </i>
              <div
                className='verify-sub-block'
                style={{
                  position: 'absolute',
                  width: ((this.state.setSize.imgWidth) * 47) / 310 + 'px',
                  height: this.state.setSize.imgHeight,
                  top: '-' + ((this.state.setSize.imgHeight) + vSpace) + 'px',
                  backgroundSize: this.state.setSize.imgWidth + ' ' + this.state.setSize.imgHeight,
                }}
              >
                {this.state.blockBackImgBase?<img
                  src={'data:image/png;base64,' + this.state.blockBackImgBase}
                  alt=""
                  style={{ width: '100%', height: '100%', display: 'block' }}
                />:''}
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

VerifySlide.defaultProps = {
  mode: 'fixed',
  vSpace: 5,
  imgSize: {
    width: '310px',
    height: '200px',
  },
  barSize: {
    width: '310px',
    height: '40px',
  },
  setSize: {
    imgHeight: 200,
    imgWidth: 310,
    barHeight: 0,
    barWidth: 0,
  }
};

export default VerifySlide